package com.lse_from.utils.encryption

import java.security.MessageDigest
import kotlin.jvm.Throws

/**
 * MD5带盐加密
 *
 * @author 祁雪
 */
class MD5Encryption {

    companion object {

        private val hexDigits =
            arrayOf<String>("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")

        /**
         * 加密
         *
         * @param content 内容
         * @param slat 盐
         */
        @Throws(Exception::class)
        fun encode(content: String, slat: String): String {

            val md5 = MessageDigest.getInstance("MD5")

            val data = content + byteArrayToHexString(slat.toByteArray())

            val results = md5.digest(data.toByteArray())

            return byteArrayToHexString(results)
        }


        private fun byteArrayToHexString(b: ByteArray): String {
            val resultSb = StringBuffer()
            for (i in b.indices) {
                resultSb.append(byteToHexString(b[i]))
            }
            return resultSb.toString()
        }


        private fun byteToHexString(b: Byte): String {
            var n = b.toInt()
            if (n < 0) n = 256 + n
            val d1 = n / 16
            val d2 = n % 16
            return hexDigits[d1] + hexDigits[d2]
        }

    }

}

fun main() {
    val content = "D:\\爬虫文件\\asian_to_lick"
    val slat = "cosplay"
    println(MD5Encryption.encode(content, slat))
    println(MD5Encryption.encode(content, slat))
}